/*
 * @Author: 李超越 1509572300@qq.com
 * @Date: 2024-08-24 11:40:18
 * @LastEditors: 李超越 1509572300@qq.com
 * @LastEditTime: 2024-08-24 15:39:45
 * @FilePath: /my_git/lesson29_Cond/testCond.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cerrno>
#include <sys/types.h>
#include <vector>
#include <string>
#include <functional>
using namespace std;

pthread_cond_t gcond=PTHREAD_COND_INITIALIZER;//条件变量
pthread_mutex_t gmutex=PTHREAD_MUTEX_INITIALIZER;//互斥锁

void *SlaverCore(void* args)
{
    string name=static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&gmutex);
        pthread_cond_wait(&gcond,&gmutex);
        cout<<"signl is:"<<name<<endl;
        pthread_mutex_unlock(&gmutex);
    }
}

void* MasterCore(void* args)
{
    sleep(3);
    string name=static_cast<const char*>(args);
    while(true)
    {
        pthread_cond_signal(&gcond);
        cout<<"master signl"<<endl;
        sleep(1);
    }
}

void StartSlaver(vector<pthread_t> *tids,int threadnum=3)
{
    for(int i=0;i<threadnum;i++)
    {
        char* name=new char[64];
        snprintf(name,64,"slaver-%d",i+1);
        pthread_t tid;
        int n=pthread_create(&tid,nullptr,SlaverCore,name);
        if(n==0)
        {
            cout<<"create success:"<<name<<endl;
            tids->emplace_back(tid);
        }
    }
}

void StartMaster(vector<pthread_t> *tids)
{
    pthread_t tid;
    int n=pthread_create(&tid,nullptr,MasterCore,(void*)"Master Thread");
    if(n==0)
    {
        cout<<"create master success"<<endl;
    }
    tids->emplace_back(tid);
}

void WaitThread(vector<pthread_t> &tids)
{
    for(auto tid:tids)
    {
        pthread_join(tid,nullptr);
    }
}

int main()
{
    vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlaver(&tids,5);
    WaitThread(tids);
    return 0;
}